/**
 * React Native Print Provider
 * 用于全局挂载Print系统到React应用中
 */

import React, { createContext, useContext, useEffect, useState } from 'react'
import Print from './Print'

// 创建Context
const PrintContext = createContext({
  print: Print,
  status: {
    isConnected: false,
    isOnline: true,
    queueLength: 0,
    localLogsCount: 0,
  },
  config: {},
  updateConfig: () => {},
  refreshStatus: () => {},
})

// Print Provider组件
export const PrintProvider = ({
  children,
  config = {},
  statusUpdateInterval = 5000, // 状态更新间隔，默认5秒
}) => {
  const [status, setStatus] = useState({
    isConnected: false,
    isOnline: true,
    queueLength: 0,
    localLogsCount: 0,
  })

  const [currentConfig, setCurrentConfig] = useState(config)

  // 初始化Print系统
  useEffect(() => {
    Print.init(config)

    // 初始化状态
    const initialStatus = Print.getStatus()
    setStatus(initialStatus)

    // 定期更新状态
    const statusInterval = setInterval(() => {
      const newStatus = Print.getStatus()
      setStatus(newStatus)
    }, statusUpdateInterval)

    return () => {
      clearInterval(statusInterval)
    }
  }, [config, statusUpdateInterval])

  // 更新配置的方法
  const updateConfig = (newConfig) => {
    const mergedConfig = { ...currentConfig, ...newConfig }
    setCurrentConfig(mergedConfig)
    Print.updateConfig(newConfig)
  }

  // 手动刷新状态
  const refreshStatus = () => {
    const newStatus = Print.getStatus()
    setStatus(newStatus)
  }

  // Context值
  const contextValue = {
    print: Print,
    status,
    config: currentConfig,
    updateConfig,
    refreshStatus,
  }

  return <PrintContext.Provider value={contextValue}>{children}</PrintContext.Provider>
}

// 自定义Hook用于访问Print Context
export const usePrint = () => {
  const context = useContext(PrintContext)

  if (!context) {
    throw new Error('usePrint must be used within a PrintProvider')
  }

  return context
}

// 简化的Hook，只返回print实例
export const usePrintLogger = () => {
  const { print } = usePrint()
  return print
}

// 状态Hook
export const usePrintStatus = () => {
  const { status, refreshStatus } = usePrint()
  return { status, refreshStatus }
}

// 配置Hook
export const usePrintConfig = () => {
  const { config, updateConfig } = usePrint()
  return { config, updateConfig }
}

export default PrintProvider
